import json

from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse
from django.views import View
from homes.models import House
from datetime import datetime

from ihome.utils.views import LoginRequiredMixin
from order.models import Order


class OrderView(LoginRequiredMixin, View):

    def post(self, request):
        """

        :param request: int:house_id  str:start_date,end_date
        :return: json {'data':{'order_id':1},'errno':0,'errmsg':'下单成功'}
        """

        # 接收参数
        json_dict = json.loads(request.body)
        house_id = json_dict.GET.get('house_id')
        start_date = json_dict.GET.get('start_date')
        end_date = json_dict.GET.get('end_date')

        # 校验
        if not all([house_id, start_date, end_date]):
            return JsonResponse({
                'errno': 4004,
                'errmsg': 'DATAERR'
            })

        try:
            house = House.objects.get(id=house_id)
        except Exception as err:
            return JsonResponse({
                'errno': 4001,
                'errmsg': 'DBERR'
            })

        # 校验身份
        user = request.user

        # 4103 PARAMERR 参数错误
        try:
            start_date = datetime.strptime(start_date, '%Y-%m-%d')
        except Exception as err:
            return JsonResponse({
                'errno': 4103,
                'errmsg': 'PARAMERR'
            })

        try:
            end_date = datetime.strptime(end_date, '%Y-%m-%d')
        except Exception as err:
            return JsonResponse({
                'errno': 4103,
                'errmsg': 'PARAMERR'
            })

        days = end_date - start_date

        Order.objects.create(
            user=user.id,
            house=house.id,
            begin_date=start_date,
            end_date=end_date,
            days=days,
            house_price=house.price,
            amount=house.price * days,
            status=Order.ORDER_STATUS_ENUM['WAIT_ACCEPT'],
        )

        resp_order = Order.objects.all()[0:1].order_by('-create_time')

        return JsonResponse({
            {
                "data": {
                    "order_id": resp_order.id
                },
                "errno": "0",
                "errmsg": "下单成功"
            }
        })

    def get(self, request):
        """

        :param request:
        :return:
        """
        role = request.GET.get('role')

        if not role:
            return ({
                "errno": "4002",
                "errmsg": "NODATA"
            })

        user = request.user

        if role == 'custom':
            try:
                orders = Order.objects.filter(user_id=user.id)
            except Exception as err:
                return ({
                    "errno": "4001",
                    "errmsg": "DBERR"
                })

        elif role == 'landlord':
            try:
                house = House.objects.get(user_id=user.id)
                orders = Order.objects.filter(house_id=house.id)
            except Exception as err:
                return ({
                    "errno": "4001",
                    "errmsg": "DBERR"
                })

        else:
            return ({
                "errno": "4105",
                "errmsg": "ROLEERR"
            })

        data = {}
        orders_list = []

        for order in orders:
            house = House.objects.get(id=order.house_id)
            orders_list.append({
                "amount": order.amount,
                "comment": order.comment,
                "ctime": order.create_time,
                "days": order.days,
                "end_date": order.end_date,
                "img_url": '',
                "order_id": order.id,
                "start_date": order.begin_date,
                "status": order.status,
                "title": house.title
            })

        data['orders'] = orders_list

        return ({
            "errno": "0",
            "errmsg": "ok",
            "data": data
        })

# # class OrderListView(LoginRequiredMixin, View):
# class OrderListView(View):
